<template>
  <div ref="bar" class="chart"></div>
</template>
<script setup>
import { ref, defineProps, onMounted, watch } from 'vue';
import * as eCharts from 'echarts';

const bar = ref(null);
const _option = {
  grid: {
    left: 26,
    right: 26,
    top: 26,
    bottom: 36
  },
  textStyle: {
    fontSize: '0.875rem',
    color: 'white'
  },
  tooltip: {
    trigger: 'axis'
  },
  yAxis: {
    type: 'value',
    axisLine: {
      show: true,
      lineStyle: {
        color: 'white'
      }
    },
    splitLine: {
      show: false
    },
    name: '单位：(次)',
    nameTextStyle: {
      align: 'left',
      verticalAlign: 'top',
      padding: [0, 0, 0, 20]
    }
  },
  xAxis: {
    type: '',
    axisLine: {
      show: true,
      lineStyle: {
        color: 'white'
      }
    },
    axisTick: {
      alignWithLabel: true,
      lineStyle: {
        color: 'white'
      }
    }
  }
};

const props = defineProps({
  marge: {
    type: Boolean,
    default: true
  },
  option: {
    type: Object,
    default: () => {
      return {};
    }
  }
});

watch(() => props.option, (v) => {
  if (chart) {
    const { marge, option } = props;
    const chartOption = marge ? deepObjectMerge(_option, option) : option;
    chart.setOption(chartOption);
  }
});

let chart;
onMounted(() => {
  const barDom = bar.value;
  chart = eCharts.init(barDom);
  const { marge, option } = props;
  const chartOption = marge ? deepObjectMerge(_option, option) : option;
  chart.setOption(chartOption);
});

const deepObjectMerge = (targ, sour) => {
  const source = JSON.parse(JSON.stringify(sour));
  const target = targ;
  for (const key in source) {
    if (key.hasOwnProperty) {
      target[key] =
        target[key] && typeof target[key] === 'object'
          ? deepObjectMerge(target[key], source[key])
          : (target[key] = source[key]);
    }
  }
  return target;
};

</script>
<style lang="less" scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
